﻿using UnityEngine;
using System.Collections;

public class enemy : MonoBehaviour {

	public GameObject player;
	public Vector3 target;
	public Material danger_mat;
	public Material safe_mat;

	public float delay=0f;

	// Use this for initialization
	void Start () {
	
		player=GameObject.FindGameObjectWithTag("Player");


		target = transform.position;

		transform.localScale*=0.9f+(Random.Range(0f,10f)/5f);

	}
	
	// Update is called once per frame
	void FixedUpdate () {


		// liikkuminen
		if((delay-=(1f/60f))<=0.0f && player!=null)
		{
			float s=1f;
			delay=Random.Range(1f,10f);
			target.x=Random.Range(player.transform.position.x-s,player.transform.position.x+s);
			target.y=Random.Range(player.transform.position.y-s,player.transform.position.y+s);
		}

		Vector3 dir = transform.position - target;
		dir.Normalize();
		dir*=-0.5f*transform.localScale.x;
		rigidbody2D.AddForce(dir);

		if(player!=null)
		{
			if(player.transform.localScale.x>=transform.localScale.x)
			{
				renderer.material=safe_mat;
			}
			else
			{
				renderer.material=danger_mat;
			}
		}

		// tuhotaan liiaan kaukana
		if(Vector3.Distance(player.transform.position,transform.position)> player.transform.localScale.x+transform.localScale.x+Camera.main.orthographicSize*3f)
			Destroy (gameObject);
	}


}
